/** 导出文件
 * @param blob 文件流
 * @param fileName 文件名
 */
export const saveByBlob = (blob: Blob, fileName: string) => {
  if ("download" in document.createElement("a")) {
    const elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  } else {
    // @ts-ignore
    window.navigator.msSaveBlob(blob, fileName);
  }
}
/** Blob下载文件，会唤起文件选择框，可以选择保存路径
 * @param data 数据流
 * @param type MIME类型，参考：http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
 * @param fileName 文件名
 */
export async function saveByBlobV2(data: string, type: string, fileName: string) {
  const BlobData = new Blob([data], { type });

  if (window.showSaveFilePicker) {
    const fileHandle = await window.showSaveFilePicker({
      suggestedName: fileName.toLowerCase(),
      types: [
        {
          description: `${fileName}文件下载`,
          // accept: {'text/plain': ['.txt']},
        },
      ],
    });
    const writableFileStream = await fileHandle.createWritable();
    await writableFileStream.write(BlobData);
    await writableFileStream.close();
  } else {
    const btn = document.createElement('a')
    btn.href = URL.createObjectURL(BlobData)
    btn.download = fileName.toLowerCase();
    btn.click()

    URL.revokeObjectURL(btn.href)
  }
}

/** 将B转为对应单位值
 * @param [num=0] B值
 * @example num2SizeUnit(1024) // 1K
 */
export function num2SizeUnit(num = 0) {
  if (num < 1024) return `${num}B`
  if (num < 1024 * 1024) return `${num / 1024}K`
  if (num < 1024 * 1024 * 1024) return `${num / 1024 / 1024}M`
  if (num < 1024 * 1024 * 1024 * 1024) return `${num / 1024 / 1024 / 1024}G`
  if (num < 1024 * 1024 * 1024 * 1024 * 1024) return `${num / 1024 / 1024 / 1024 / 1024}T`
}
/** 单位值转xB
 * @param [str=''] 单位值
 * @example sizeUnit2num('1K') // 1024
 */
export function sizeUnit2num(str = '') {
  const unitStr = str.replace(/[.|0-9]/g, '').toUpperCase()
  if (unitStr === 'B') return parseFloat(str)
  if (unitStr === 'K') return parseFloat(str) * 1024
  if (unitStr === 'M') return parseFloat(str) * 1024 * 1024
  if (unitStr === 'G') return parseFloat(str) * 1024 * 1024 * 1024
  if (unitStr === 'T') return parseFloat(str) * 1024 * 1024 * 1024 * 1024
}